<?php
namespace App\Admin\Actions;

use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;


/**
 * 后台通用删除功能
 */
trait Delete
{


	public function delete(Request $request, ActionSetter $setter)
	{
		$this->initDeleteAction();

		// 默认配置器与自定义配置器
		$this->setDeleteDefaultSetter($setter);
		if( method_exists($this, 'actionDelete') ){
			$this->actionDelete($setter);
		}

		$pkValues = $setter->call('pkValues', $request);
		abort_if(empty($pkValues), 422, '缺少参数: 要删除的记录id');


		/**
		 * 先查询出结果
		 * 如果开启了批量删除返回Collection，否则返回Model
		 */
		$eloquent = $setter->call('find', $pkValues);
		// $models = $this->modelName()::find(38);



		// 前置操作
		$setter->call('before', $eloquent);

		// 删除的真实操作
		$setter->call('handle', $eloquent);

		// 
		$setter->call('after');


		return [
			'code' => 0,
			'message' => 'success',
			'data' => $eloquent->count()
		];
		return [
			'pkValues' => $pkValues,
			'models' => $eloquent,
		];
	}


	private function setDeleteDefaultSetter($setter)
	{
		$setter->pkValues([$this, 'deleteGetPkValues']);
		$setter->find([$this, 'deleteFind']);
		$setter->handle([$this, 'deleteHandle']);
	}

	/**
	 * 根据主键查询出要删除的数据eloquent集合
	 */
	public function deleteFind($pkValues):Collection
	{ 
		return $this->modelName()::find($pkValues);
	}

	/**
	 * 获得要删除的数据数组(在数据库中的主键值)
	 */
	public function deleteGetPkValues(Request $request)
	{
		return $request->input('id');
	}

	/**
	 * 执行删除操作
	 */
	public function deleteHandle(Collection|Model $eloquent)
	{
		if ($eloquent instanceof Model) {
			return $eloquent->delete();
		}else{
			$eloquent->each(function($model, $key){
				$model->delete();
			});
		}
	}



	private function initDeleteAction()
	{
		$class_name = __CLASS__;

		abort_unless(method_exists($this, 'modelName'), 500, "{$class_name} 未设置 modelName() 方法");
	}
}

